package com.aaa.mysecurity.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author ：ludi（206913808@qq.com）
 * @date ：Created in 2022/11/2 15:39
 * @description：JWT工具类
 * @modified By：
 * @version:
 */
public class JwtUtil {


    private static String sign = "ld";


    /**
     * @create by: ludi（206913808@qq.com）
     * @description: 生成jwt
     * @create time: 2022/11/2 17:01
     * @param map
     * @return java.lang.String
     */
    public static String createJWT(Map<String,Object> map){
        /**
         * 头信息
         */
        Map<String,Object> head = new HashMap();
        head.put("alg", "HS256");
        head.put("typ", "JWT");
        /**
         * 颁发时间
         */
        Date iat = new Date();
        /**
         * 过期时间
         */
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.SECOND,7200);
        Date time = instance.getTime();
        String token = JWT.create()
                /**
                 * 头信息
                 */
                .withHeader(head)
                /**
                 * 颁发时间
                 */
                .withIssuedAt(iat)
                /**
                 * 过期时间
                 */
                .withExpiresAt(time)
                /**
                 * 自定义的内容
                 */
                .withClaim("loginInfo", map)
                /**
                 * 签名
                 */
                .sign(Algorithm.HMAC256(sign));
                return token;
    }

    /**
     * @create by: ludi（206913808@qq.com）
     * @description: 校验token是否有效
     * @create time: 2022/11/2 16:11
     * @param token
     * @return boolean
     */
    public static boolean verifyToken(String token){
        /**
         * 获取一个校验对象
         */
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        try {
            DecodedJWT verify = build.verify(token);
            return true;
        }
        catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    /**
     * @create by: ludi（206913808@qq.com）
     * @description: 从token中获取相应的载荷内容
     * @create time: 2022/11/2 16:14
     * @param token
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    public static Map<String,Object> getTokenChaim(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        /**
         * 调用校验功能
         */
        DecodedJWT verify = build.verify(token);
        Claim loginInfo = verify.getClaim("loginInfo");
        return loginInfo.asMap();
    }

}